package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author likepei
 * @Date 2020/2/21 10:29
 * @Version v1.0
 * @Description 图表的控制器
 */
@RestController
@Slf4j
@RequestMapping("/report")
public class ReportController {

    @Reference
    private ReportService reportService;
    @Reference
    private MemberService memberService;

    /**
     * @Author MH
     * @Version v1.0
     * @Description 一段时间内查看人数
     */
    @RequestMapping("minAndMax")
    public Result minAndMax( @RequestBody Map<String,String> dateString) {
        try {
            String min = dateString.get("min");
            String max = dateString.get("max");
            //使用日期格式化类SimpleDateFormat转换时间，指定格式为yyyy-MM-dd
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            Date minDate = simpleDateFormat.parse(min);
            Date maxDate = simpleDateFormat.parse(max);

            System.out.println(min + "=============" + max);
            System.out.println(minDate + "=============" + maxDate);

            List<String> monthList = new ArrayList<>();

            //两者的月份差
            Long cha = (((maxDate.getTime() - minDate.getTime()) / (24 * 60 * 60 * 1000)) / 30);
            int count = cha.intValue();

            //遍历最小月份
            for (int i = 0; i <= count; i++) {
                Date parse = simpleDateFormat.parse(min);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parse);

                if (i!=0 && i<13){
                    calendar.add(Calendar.MONTH,+i);
                }
                parse = calendar.getTime();

                if (i == 13) {
                    calendar.add(Calendar.YEAR,1);
                    calendar.add(Calendar.MONTH,-12);
                    parse = calendar.getTime();
                }
                monthList.add(simpleDateFormat.format(parse));
            }


            List<Integer> memberCount = reportService.findMinAndMax(monthList);
            //返回报表数据
            Map<String, Object> map = new HashMap<>();
            map.put("months", monthList);
            map.put("memberCount", memberCount);

            return new Result(true, "查询成功!", map);
        } catch (ParseException e) {
            e.printStackTrace();
            return new Result(true, "查询失败!");
        }
    }

    /**
     * 运营数据统计报表导出
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){
        try {
            //调用Service，获取统计数据
            Map<String, Object> reportData = reportService.getBusinessReportData();
            //获得报表日期
            String reportDate = (String) reportData.get("reportDate");
            //获取与会员有关数据 (今日、本周、本月、总人数)
            Integer todayNewMember = (Integer) reportData.get("todayNewMember");
            Integer thisWeekNewMember = (Integer) reportData.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) reportData.get("thisMonthNewMember");
            Integer totalMember = (Integer) reportData.get("totalMember");
            //获取与预约有关数据 (今日、本周、本月)
            Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
            //获得到诊相关数据 (今日、本周、本月)
            Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
            //获得套餐热门数据
            List<Map<String,Object>> hotSetmealList = (List<Map<String, Object>>) reportData.get("hotSetmeal");

            //利用POIUtils写入数据到Excel
            InputStream inputStream = ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            //利用流，读Excel文件，构建XSSFWorkbook对象，获取工作表
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取报表日期行
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);
            //获取新增会员及会员总数行
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            //获取本周新增会员及本月新增会员行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);
            //获取今日预约及到诊数行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            //获取本周预约及到诊数行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            //获取本月预约及到诊行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);
            //获取热门套餐行，动态写入数据
            //设置起始行号
            int startRowNumber = 12;
            for (Map<String, Object> hotSetmeal : hotSetmealList) {
                //获取名称, 数量, 占比, 备注
                String name = (String) hotSetmeal.get("name");
                Long setmeal_count = (Long) hotSetmeal.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) hotSetmeal.get("proportion");
                String remark = (String) hotSetmeal.get("remark");

                //指定行号
                row = sheet.getRow(startRowNumber);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                row.getCell(7).setCellValue(remark);

                startRowNumber++; //行号+1
            }


            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");

            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

            return new Result(true, MessageConst.ACTION_SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 获取运营数据统计信息
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            //调用service, 获取到页面中 需要的所有数据 (Map集合)
            Map<String, Object> map = reportService.getBusinessReportData();
            //获取成功, 返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //获取失败, 返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }

    /**
     * 获取套餐的占比信息
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            //调用Service , 得到 套餐占比数据
            List<Map<String,Object>> setmealCount = reportService.findSetmealCount();

            //定义一个集合, 用于存储套餐的名称
            List<String> setmealNames = new ArrayList<>();
            //循环, 得到每一个套餐占比信息
            for (Map<String, Object> setmealMap : setmealCount) {
                //把每一个套餐的名称, 存到到套餐名称的集合中
                setmealNames.add((String) setmealMap.get("name"));
            }

            Map<String, Object> map = new HashMap<>();
            map.put("setmealNames", setmealNames);
            map.put("setmealCount", setmealCount);

            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);

        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 获取会员数量信息( 最近12个月)
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            //构造月份列表
            //1.获取当前日期 (日历对象)
            Calendar calendar = Calendar.getInstance();
            // 返回到12个月之前的日期
            calendar.add(Calendar.MONTH, -12);

            List<String> monthList = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                //把当前日历的月份 + 1
                calendar.add(Calendar.MONTH, 1);
                //把月份变化后的当前日期, 存入到 monthList集合中
                Date date = calendar.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
                monthList.add(sdf.format(date));
            }

            //调用Service, 获取月份列表的会员数量
            List<Integer> memberCount = reportService.findMemberCountByMonth(monthList);

            //返回报表数据
            Map<String, Object> map = new HashMap<>();
            map.put("months", monthList);
            map.put("memberCount", memberCount);
            //返回成功信息
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }

    }
    /**
     * 会员年龄比例
     */
    @RequestMapping("/getMemberAGEReport")
    public Result getMemberAGEReport(){
        try {
            List<Map<String,Object>> mapList = new ArrayList<>();
            Map<String,Object> map1 = new HashMap<>();
            Map<String,Object> map2 = new HashMap<>();
            Map<String,Object> map3 = new HashMap<>();
            Map<String,Object> map4 = new HashMap<>();
            //定义集合
            List<String> ageList = new ArrayList<>();
            //从数据库查询到的身份证号
            List<String> list = memberService.findIdCard();
            int count1 = 0;
            int count2 = 0;
            int count3 = 0;
            int count4 = 0;
            Date date = Calendar.getInstance().getTime();
            String date2String = DateUtils.parseDate2String(date);
            String time = date2String.substring(0,4);
            for (String str : list) {
                String  birthday =  str.substring(6,10);
                //获取当前时间
                int num =Integer.parseInt(time) - Integer.parseInt(birthday);
                if (num>0 && num<18){
                    ageList.add("0~18");
                    count1++;
                    map1.put("name","0~18");
                    map1.put("value",count1);
                }else if (num>18 && num <30){
                    ageList.add("18~30");
                    count2++;
                    map2.put("name","18~30");
                    map2.put("value",count2);
                }else if (num>30&&num<45){
                    ageList.add("30~45");
                    count3++;
                    map3.put("name","30~45");
                    map3.put("value",count3);
                }else if (num>45&&num<100){
                    ageList.add("45以上");
                    count4++;
                    map4.put("name","45以上");
                    map4.put("value",count4);
                }
            }
            mapList.add(map1);
            mapList.add(map2);
            mapList.add(map3);
            mapList.add(map4);
            //定义集合封装返回
            Map<String,Object> map = new HashMap<>();
            map.put("age",ageList);
            map.put("membercount",mapList);
            return new Result(true,MessageConst.ACTION_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }


    /**
     * 会员男女比例
     */
    @RequestMapping("/getMemberBLReport")
    public Result getMemberBLReport(){
        try {
            //查询到数据集合
            List<Map<String,Object>> list = memberService.findMemerCount();
            //遍历集合 并添加到包含性别和数据集合的map集合中
            //定义集合 用来重新定义membercount中数据
            Map<String,Object> sexMap1= new HashMap<>();
            Map<String,Object> sexMap2= new HashMap<>();
            //定义集合添加sex性别
            List<String> sexList = new ArrayList<>();

            for (Map<String, Object>  countMap : list) {
                String sex = (String) countMap.get("name");
                Object value = countMap.get("value");
                if (Integer.parseInt(sex)==1){
                    sexList.add("男");
                    sexMap1.put("name","男");
                    sexMap1.put("value",value);
                }else {
                    sexList.add("女");
                    sexMap2.put("name","女");
                    sexMap2.put("value",value);
                }
            }
            list.clear();
            list.add(sexMap1);
            list.add(sexMap2);
            //数据的返回
            Map<String,Object> map = new HashMap<>();
            map.put("sex",sexList);
            map.put("membercount",list);

            //System.out.println(sexList.toString());
            //System.out.println("map = " + map);


            return new Result(true,MessageConst.ACTION_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

}
